﻿using System;
using System.Collections.Generic;
using Eventd.Socket;
using Shot.Session;
using Shot.Session.Cookies;

namespace Shot
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    public delegate void ReadyEventArgs(object sender);

    /// <summary>
    /// Represents an instance of an App, and a connected client to the server.
    /// </summary>
    public class AppInstance : EventdClient
    {
        /// <summary>
        /// AppInstance's root App
        /// </summary>
        public App App { get; set; }

        /// <summary>
        /// CookieManager Instance
        /// </summary>
        public CookieManager Cookie { get; set; }

        /// <summary>
        /// SessionManager Instance
        /// </summary>
        public SessionManager Session { get; set; }

        /// <summary>
        /// Instance specific temporary data.
        /// </summary>
        public Dictionary<string, object> Data { get; set; } 

        /// <summary>
        /// Triggered when application has finished setup.
        /// </summary>
        public event ReadyEventArgs Ready;

        /// <summary>
        /// Initialize the application
        /// </summary>
        public AppInstance()
        {
            Session = new SessionManager { Instance = this };
            Cookie = new CookieManager { Instance = this };
            Data = new Dictionary<string, object>();
        }

        /// <summary>
        /// Set up the session
        /// </summary>
        public void After()
        {
            Cookie.Get("ShotSession", SessionCallback);
        }

        private void SessionCallback(dynamic returnedSessionKey)
        {
            if (((String)returnedSessionKey).Equals(""))
            {
                var sessionKey = Guid.NewGuid().ToString();
                Cookie.Set("ShotSession", sessionKey);
                Session.SessionKey = sessionKey;
            }

            else
            {
                Session.SessionKey = (String)returnedSessionKey;
            }

            Ready.Invoke(this);
        }
    }
}
